<template>
  <div align="center">
    <el-steps :active="active" finish-status="success" align-center>
      <el-step title="选择商品分类"></el-step>
      <el-step title="填写商品信息"></el-step>
      <el-step title="填写商品属性"></el-step>
    </el-steps>
    <!-- 这是步骤一 -->
	<el-card v-show="active == 0" style="width: 1000px; margin-top: 30px;">
		<el-cascader-panel style="width: 580px; margin-top: 20px;"
		  v-model="value"
		  :options="categories"
		  @change="handleChange()"
		></el-cascader-panel>
		<span class="sp">您当前选择的商品类别是：{{ activeOneCategory }} > {{ activeTwoCategory }} > {{ activeSanCategory }}</span>
		<br />
		<el-button style="margin-top: 250px;" @click="active = 1; getBrand()" type="primary">下一步，填写商品属性</el-button>
	</el-card>
    <!-- 这是步骤二 -->
	<el-card class="box-card" v-show="active == 1" style="width: 1000px; margin-top: 50px;">
	  <el-form ref="spuRef" :rules="rules" :model="spu" label-position="left" label-width="90px">
		<el-form-item label="商品分类:">
		  {{ activeOneCategory }} > {{ activeTwoCategory }} > {{ activeSanCategory }}
		  <el-button icon="el-icon-edit-outline" size="mini" type="primary" @click="active = 0">编辑</el-button>
		</el-form-item>
		<el-form-item label="商品名称:" prop="name">
		  <el-input v-model="spu.name"></el-input>
		</el-form-item>
		<el-form-item label="副标题:" prop="caption">
		  <el-input v-model="spu.caption"></el-input>
		</el-form-item>
		<el-form-item label="商品品牌:" prop="brandId">
		  <el-select v-model="spu.brandId" placeholder="请选择商品品牌" style="width: 100%;" clearable>
			<el-option v-for="item in brands" :key="item.id" :label="item.name" :value="item.id"></el-option>
		  </el-select>
		</el-form-item>
		<el-form-item label="商品介绍:">
		  <el-input
			type="textarea"
			min="5"
			max="5"
			v-model="spu.introduction"
		  ></el-input>
		</el-form-item>
		<el-form-item label="运费模板:" prop="freightId">
		  <el-select v-model="spu.freightId" placeholder="请选择运费模板" style="width: 100%;">
			<el-option label="模板一" :value="10"></el-option>
		  </el-select>
		</el-form-item>
		<el-form-item label="商品货号:">
		  <el-input v-model="spu.sn"></el-input>
		  <span style="font-size: 12px; color: red;">*如果您不输入商品货号，系统将自动生成一个唯一的账号</span>
		</el-form-item>
		<el-form-item label="服务保证:">
		  <el-checkbox-group v-model="saleService">
		      <el-checkbox label="无忧退货" value="无忧退货"></el-checkbox>
		      <el-checkbox label="快速退款" value="快速退款"></el-checkbox>
		      <el-checkbox label="免费包邮" value="免费包邮"></el-checkbox>
		    </el-checkbox-group>
		</el-form-item>
		<el-form-item>
		  <el-button @click="active = 0">上一步，选择商品分类</el-button>
		  <el-button type="primary" @click="getNext('spuRef')">下一步，填写商品属性</el-button>
		</el-form-item>
	  </el-form>
	</el-card>
	<!-- 这是步骤三 -->
	<el-card class="box-card" v-show="active == 2" style="width: 1000px; margin-top: 50px;">
		<!-- 这是商品规格区域 -->
		<el-card>
			*商品规格
			<div align="left" v-for="item in checkList" :key="item.id">
				{{ item.name }}
				<el-checkbox-group v-model="checkboxGroup" @change="chekedChange()">
				  <el-checkbox v-for="city in item.options" :label="city" :key="city">{{ city }}</el-checkbox>
				</el-checkbox-group>
			</div>
		</el-card>
		<el-card style="margin-top: 20px;">
			<!--表格-->
			<el-table :data="myary" style="width: 100%">
			   <el-table-column v-for="(col) in specNames" :label="col.label" :key="col.label">
			       <template slot-scope="scope">
			          {{ scope.row[col.prop] }}
			       </template>
			    </el-table-column>
			     <el-table-column label="价格" width="180">
			        <template slot-scope="scope">
			            <el-input size="small" v-model="scope.row.price" placeholder="请输入单价"></el-input>
			        </template>
			    </el-table-column>
			     <el-table-column label="库存数量" width="180">
			        <template slot-scope="scope">
			            <el-input size="small" v-model="scope.row.num" placeholder="请输入库存数量"></el-input>
			        </template>
			    </el-table-column>
				<el-table-column label="库存预警值" width="180">
				    <template slot-scope="scope">
				        <el-input size="small" v-model="scope.row.alertNum" placeholder="请输入库存预警值"></el-input>
				    </template>
				</el-table-column>
			</el-table>
		</el-card>
		<!-- 这是商品参数区域 -->
		<el-card style="margin-top: 20px;">
			*商品参数
			<!--表格-->
			<el-table :data="paras" style="width: 100%">
				<el-table-column label="参数类型" width="180" prop="name"></el-table-column>
				<el-table-column label="录入参数" width="180">
				    <template slot-scope="scope">
						<el-select v-model="para[scope.row.id]" placeholder="请选择">
						  <el-option v-for="(item, index) in scope.row.paraOption" :key="index" :label="item" :value="item"></el-option>
						</el-select>
				    </template>
				</el-table-column>
			</el-table>
		</el-card>
		<!-- 这是商品相册区域 -->
		<el-card style="margin-top: 20px;">
			<p>*商品相册</p>
			<div>
				<div class="p" v-for="(image, index) in imageAry" :key="index">
					<el-image style="height: 140px;" :src="image" fit="fit"></el-image>
					<p style="height: 20px; width: 150px;">
						<a style="font-size: 12px;" v-if="index == 0">商品主图</a>
						<a href="#" @click="setImageOne(index)" style="font-size: 12px;" v-else>设置主图</a> | 
						<a style="font-size: 12px;">删除图片</a>
					</p>
				</div>
			</div>
			<el-upload style="margin-top: 20px;" 
			  class="upload-demo"
			  action="http://localhost:88/api/oss"
			  :on-preview="handlePreview"
			  :on-remove="handleRemove"
			  :before-upload="beforeAvatarUpload"
			  :on-success="handleAvatarSuccess"
			  :show-file-list="false">
			  <el-button size="small" type="primary">点击上传</el-button>只能上传jpg/png文件，且不超过500kb,最多可以上传5张图片
			</el-upload>
		</el-card>
		<el-button @click="active = 1">上一步，填写商品属性</el-button>
		<el-button v-if="butShow == 1" type="primary" @click="commit()">提交审核</el-button>
		<el-button v-else-if="butShow == 2" type="primary" @click="goback()">返回商品列表</el-button>
		<el-button v-else-if="butShow == 3" type="primary" @click="commit()">修改提交</el-button>
	</el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
	  // 判断当前是什么操作
	  butShow: 1,
	  // 富文本编辑器
	  disabled: false,
	  baseUrl: process.env.NODE_ENV === 'production' ? '/testtinymce' : '',
	  language: 'zh_CN',
	  skin: 'oxide',
	  description: '',
	  // 当前步骤
      active: 0,
	  // 所有分类
      categories: [],
	  // 二级分类
      twoCategories: [],
	  // 三级分类
      sanCategories: [],
	  // 选中的一级分类
      activeOneCategory: "",
	  // 选中的二级分类
      activeTwoCategory: "",
	  // 选中的三级分类
      activeSanCategory: "",
	  // 选中的分类的值
      value: [1, 2, 3],
	  // 所有获取到的规格列表
	  spec: [],
	  // 自定义封装规格列表
	  checkList: [],
	  // 装规格列表
	  checkboxGroup: [],
	  // 规格名称数组
	  specNames: [],
	  // 临时存放规格数组
	  option: [],
	  // 用于存放计算笛卡尔积之后的规格数组
	  myary: [],
	  // 品牌列表
	  brands: [],
	  // 存放规格数组的用于计算笛卡尔积
	  ary: [],
	  // 参数列表
	  paras: [],
	  // 参数列表选项
	  paraOptions: [],
	  // 参数对象
	  para: [],
	  imageAry: [],
	  // goods对象
	  goods: {},
	  // 复选框数组
	  saleService: ['无忧退货'],
	  // spu对象
	  spu: {
		  name: '',
		  caption: '',
		  branId: '',
		  freight_id: ''
	  },
	  // skuList数组
	  skuList: [],
	  // 表单验证
	  rules: {
		name: [
		  { required: true, message: '请输入商品名称', trigger: 'blur' }
		],
		caption: [
		  { required: true, message: '请输入副标题', trigger: 'blur' }
		],
		brandId: [
		  { required: true, message: '请选择商品品牌', trigger: 'change' }
		],
		freightId: [
		  { required: true, message: '请选择运费模板', trigger: 'change' }
		]
	  },
	  // 从商品列表跳转获取的值
	  querySpuId: this.$route.query.spuId,
	  // 跳转是修改还是查看
	  handel: this.$route.query.handel
    }
  },
  methods: {
	// 步骤二下一步
	getNext (formName) {
		this.$refs[formName].validate((valid) => {
		  if (valid) {
			this.active = 2
			this.getSpec()
			this.getPara()
		  } else {
			this.$message.error("请将必填选项填写完整")
			return false
		  }
		})
	},
	// 鼠标单击的事件
	onClick (e, editor) {
		console.log('Element clicked')
		console.log(e)
		console.log(editor)
	},
	// 设置图片为主图
	setImageOne (index) {
		const oneUrl = this.imageAry[index]
		const zeroUrl = this.imageAry[0]
		this.imageAry[index] = zeroUrl
		this.imageAry[0] = oneUrl
		console.log(this.imageAry)
	},
	// 文件列表移除文件时的钩子
	handleRemove(file, fileList) {
		console.log(file, fileList)
	},
	// 点击文件列表中已上传的文件时的钩子
	handlePreview(file) {
		console.log(file)
	},
	// 上传成功的方法
	handleAvatarSuccess(file) {
	  this.imageAry.push(file.data.fileUrl)
	  // this.goods.images += file.data.fileUrl + ','
	},
	// 上传之前的方法
	beforeAvatarUpload(file) {
	  const isJPG = file.type === "image/jpeg";
	  const isLt2M = file.size / 1024 / 1024 < 2
	  const arylen = this.imageAry.length == 5
	
	  if (!isJPG) {
	    this.$message.error("上传图片只能是 JPG 格式!")
	  }
	  if (!isLt2M) {
	    this.$message.error("上传图片大小不能超过 2MB!")
	  }
	  if (arylen) {
		this.$message.error("最多只能上传五张图片")
	  }
	  return isJPG && isLt2M && !arylen
	},
	async getPara () {
		// 获取到分类对象
		const categoryId = this.value[this.value.length - 1]
		const { data: res} = await this.$http.get(`vi/goods/category/detail/${categoryId}`)
		const category = res.data.tbCategory
		// 通过模板分类对象中的模板Id查询出所有要设置的参数
		const { data: res2 } = await this.$http.get(`vi/goods/para/selectParaByTemplateId/${category.templateId}`)
		this.paras = res2.data.paras
		for (var i = 0; i< this.paras.length; i++) {
			const option = this.paras[i].options.split(',');
			this.paras[i].paraOption = option
		}
		if (this.querySpuId) {
			// 循环参数
			const paras = JSON.parse(this.spu.paraItems)
			// 回显参数
			for (var i = 0; i< this.paras.length; i++) {
				const pname = this.paras[i].name
				const pid = this.paras[i].id
				// console.log(paras[pname])
				this.para[pid] = paras[pname][0]
			}
			// console.log(this.para)
		}
	},
	expand () {
		this.ary = []
		this.myary = []
		if (this.checkList.length < 2) {
			for (let i = 0; i < this.checkboxGroup.length; i++) {
				var obj = {}
			    const prop = this.specNames[0].prop
			    obj[prop] = this.checkboxGroup[i] // 为obj设置属性及属性值
				this.myary.push(obj)
			}
			return
		}
		// 循环出单独的规格对象
		for (var prop in this.checkList) {
			// 通过单独对象获取到规格数组
			for (var item in this.checkList[prop]) {
				// 判断是否是规格数组
				if (this.checkList[prop][item] instanceof Array) {
					// 得到数组的长度
					this.checkList[prop][item].forEach(element => {
						// 判断如果选中就添加当临时规格数组中
						for (let i = 0; i < this.checkboxGroup.length; i++) {
							if (this.checkboxGroup[i] === element) {
								this.option.push(this.checkboxGroup[i])
							}
						}
					})
					this.ary.push(this.option)
					// 将临时存放规格数组清空
					this.option = []
				}
			}
		}
		// 计算笛卡尔积
		this.ary = this.calcDescartes(this.ary)
	    for (let i = 0; i < this.ary.length; i++) {
			var obj = {}
			for (let j = 0; j < this.ary[i].length; j++) {
			  const prop = this.specNames[j].prop
			  obj[prop] = this.ary[i][j] // 为obj设置属性及属性值
			}
			this.myary.push(obj)
	    }
	},
	// 计算笛卡尔积
	calcDescartes (array) {
	  if (array.length < 2) return array[0] || []
		return [].reduce.call(array, function (col, set) {
			var res = []
			col.forEach(function (c) {
				set.forEach(function (s) {
					var t = [].concat(Array.isArray(c) ? c : [c])
					t.push(s)
					res.push(t)
				})
			})
		return res
	  })
	},
	// 初始化品牌列表
	async getBrand () {
		const categoryId = this.value[this.value.length - 1]
		const { data: res } = await this.$http.get('vi/goods/brand/list')
		this.brands = res.data.list
	},
	// 初始化规格列表
	async getSpec () {
		this.checkList = []
		this.specNames = []
		const categoryId = this.value[this.value.length - 1]
		const { data: res} = await this.$http.get(`vi/goods/category/detail/${categoryId}`)
		const category = res.data.tbCategory
		// 通过模板Id获取到规格列表
		const { data: res2 } = await this.$http.get(`vi/goods/spec/selectSpecByTemplateId/${category.templateId}`)
		this.spec = res2.data.specs
		// 封装自定义模板对象
		for (var i = 0; i < this.spec.length; i++) {
			const options = this.spec[i].options.split(',')
			var check = {'name': this.spec[i].name, 'options': options, 'id': this.spec[i].id}
			// 封装了specname
			var name = {'label': this.spec[i].name, 'prop': this.spec[i].name}
			this.checkList.push(check)
			this.specNames.push(name)
		}
		if (this.querySpuId) {
			const specItems = JSON.parse(this.spu.specItems)
			for (var prop in this.specNames) {
				const spec = this.specNames[prop].label
				for (var item in specItems[spec]){
					this.checkboxGroup.push(specItems[spec][item])
				}
			}
			for (var i = 0; i < this.myary.length; i++) {
				const spec = JSON.parse(this.myary[i].spec)
				for (var prop in this.specNames) {
					const item = this.specNames[prop].label
					this.myary[i][item] = spec[item]
				}
			}
		}
	},
    // 初始化商品分类
    async getCategory() {
      const { data: res } = await this.$http.get(
        "vi/goods/category/queryAllCategory"
      )
      this.categories = res.data.maps
      this.getActiveCategory()
    },
    // 获取到所有分类的值
    handleChange() {
      this.activeOneCategory = ""
      this.activeTwoCategory = ""
      this.activeSanCategory = ""
      this.getActiveCategory()
    },
    // 获取到当前选中的分类
    getActiveCategory() {
      // 获取一级分类选中的值
      for (var i = 0; i < this.categories.length; i++) {
        // 获取到一级分类下的所有二级分类
        // 判断当前一级分类下是否存在二级分类
        if (this.categories[i].children) {
          this.twoCategories = this.categories[i].children;
          // 获取二级分类选中的值
          for (var j = 0; j < this.twoCategories.length; j++) {
            // 获取到三级分类下的所有三级分类
            // 判断当前二级分类下是否存在三级分类
            if (this.twoCategories[j].children) {
              this.sanCategories = this.twoCategories[j].children
            }
            // 判断是否选中了二级分类
            if (this.value[1]) {
              // 选中了则获取到当前选中的二级分类
              if (this.twoCategories[j].value === this.value[1]) {
                this.activeTwoCategory = this.twoCategories[j].label
              }
            }
            // 获取三级分类选中的值
            for (var k = 0; k < this.sanCategories.length; k++) {
              // 判断是否选中了三级分类
              if (this.value[2]) {
                // 选中了则获取到当前选中的三级分类
                if (this.sanCategories[k].value === this.value[2]) {
                  this.activeSanCategory = this.sanCategories[k].label
                }
              }
            }
          }
        }
        // 判断是否选中了一级分类
        if (this.value[0]) {
          // 选中了则获取到当前选中的一级分类
          if (this.categories[i].value === this.value[0]) {
            this.activeOneCategory = this.categories[i].label
          }
        }
      }
    },
    onSubmit() {
      console.log("submit!")
    },
	chekedChange () {
	  this.expand()
	},
	// 最后提交方法
	async commit () {
		// 获取模板Id
		const categoryId = this.value[this.value.length - 1]
		const { data: res} = await this.$http.get(`vi/goods/category/detail/${categoryId}`)
		const category = res.data.tbCategory
		// 获取品牌名称
		const { data: res1 } = await this.$http.get(`vi/goods/brand/detail/${this.spu.brandId}`)
		const brandName = res1.data.tbBrand.name
		// 封装spu数据
		// 封装商品分类Id
		this.spu.category1Id = this.value[0]
		this.spu.category2Id = this.value[1]
		this.spu.category3Id = this.value[2]
		// 封装图片
		this.spu.image = this.imageAry[0]
		// 运费模板
		this.spu.freightId = 10
		// 封装图片列表
		var images = ''
		for (var i = 0; i < this.imageAry.length; i++) {
			images += this.imageAry[i] + ','
		}
		images.RTrim(',')
		this.spu.images = images
		// 封装服务保证
		var saleService = ''
		for (var i = 0; i < this.saleService.length; i++) {
			saleService += this.saleService[i] + ','
		}
		saleService.substring(0, saleService.length - 1)
		this.spu.saleService = saleService
		// 封装模板Id
		this.spu.templateId = category.templateId
		// 封装spu中para列表
		this.spu.paraItems = ''
		// 封装skuList数组
		for (var i = 0; i < this.myary.length; i++) {
			// 封装sku图片
			this.myary[i].image = this.imageAry[0]
			// 封装sku图片列表
			this.myary[i].images = images
			// sku中的商品重量
			this.myary[i].weight = 10
			// sku中的商品品牌
			// 设置商品价格
			this.myary[i].price = this.myary[i].price * 10
			this.myary[i].brandName = brandName
			// console.log(this.myary[i][颜色])
			// 装sku中的spec
			const spec = ''
			// spec名称
			const sname = ''
			// 循环spec名称数组
			for (var j = 0; j < this.specNames.length; j++) {
				// 获取到spec名称
				sname = this.specNames[j].label.toString()
				// 封装sku中的spec
				spec += JSON.stringify(this.specNames[j].label) +':'+ JSON.stringify(this.myary[i][sname]) + ','
			}
			// 截取封装sku中spec属性
			spec = spec.substring(0, spec.length - 1)
			spec = '{' + spec + '}'
			// 讲结果添加到每一个sku对象中
			this.myary[i].spec = spec.toString()
			// 将sku添加到skulist中
			this.skuList.push(this.myary[i])
		}
		this.getSpecItems()
		this.getParaItems()
		// 封装goods
		this.goods.spu = this.spu
		this.goods.skuList = this.skuList
		const { data: response } = await this.$http.post('vi/goods/goods/save', this.goods)
		this.$message.success(response.message)
		this.$router.push('/goods/auditSpu')
	},
	// 封装spec列表
	getSpecItems () {
		// 装spu中的spec列表
		let specItems = ''
		// 装spu中的单个数组
		let specItem = []
		// spec对象
		let items = ''
		// 循环出单独的规格对象
		for (var prop in this.checkList) {
			// 通过单独对象获取到规格数组
			for (var item in this.checkList[prop]) {
				// 判断是否是规格数组
				if (this.checkList[prop][item] instanceof Array) {
					// 得到数组的长度
					this.checkList[prop][item].forEach(element => {
						// 判断如果选中就添加当临时规格数组中
						for (let i = 0; i < this.checkboxGroup.length; i++) {
							if (this.checkboxGroup[i] === element) {
								specItem.push(element)
							}
						}
					})
					// 判断当循环末尾时将临时数组添加到数组中
					items = JSON.stringify( this.checkList[prop].name ) + ':' + JSON.stringify( specItem )
					specItems += items + ','
					specItem = []
				}
			}
		}
		specItems = specItems.RTrim(',')
		specItems = '{' + specItems + '}'
		this.spu.specItems = specItems.toString()
	},
	// 封装para列表
	getParaItems () {
		// 装spu中的spec列表
		let paraItems = ''
		// 装spu中的单个数组
		let paraItem = []
		// spec对象
		let items = ''
		// 循环出单独的规格对象
		for (var prop in this.paras) {
			// 通过单独对象获取到规格数组
			for (var item in this.paras[prop]) {
				// 判断是否是规格数组
				if (this.paras[prop][item] instanceof Array) {
					// 得到数组的长度
					this.paras[prop][item].forEach(element => {
						// 判断如果选中就添加当临时规格数组中
						for (let i = 0; i < this.para.length; i++) {
							if (this.para[i] === element) {
								paraItem.push(element)
							}
						}
					})
					// 判断当循环末尾时将临时数组添加到数组中
					items = JSON.stringify( this.paras[prop].name ) + ':' + JSON.stringify( paraItem )
					paraItems += items + ','
					paraItem = []
				}
			}
		}
		paraItems = paraItems.RTrim(',')
		paraItems = '{' + paraItems + '}'
		this.spu.paraItems = paraItems.toString()
	},
	// 回显数据通过spuId
	async getGoodsBySpuId () {
		if (this.querySpuId) {
			const { data: res } = await this.$http.get(`vi/goods/spu/findGoodsById/${this.querySpuId}`)
			const spu = res.data.goods.spu
			const skuList = res.data.goods.skuList
			this.spu = spu
			this.value = [spu.category1Id, spu.category2Id, spu.category3Id]
			this.saleService = spu.saleService.split(',')
			this.imageAry = this.spu.images.split(',')
			this.myary = skuList
		}
		if (this.handel) {
			if (this.handel == 'query') {
				this.butShow = 2
			}else {
				this.butShow = 3
			}
		}
	},
	goback () {
		this.$router.push('/goods/spu')
	}
  },
  created() {
	  // console.log(this.querySpuId, this.handel)
	this.getGoodsBySpuId()
    this.getCategory()
  }
};
</script>
<style scoped="scoped">
.sp {
	position: relative;
	text-align: center;
	display: block;
	top: 20px;
	font-size: 12px;
}
.p {
	border: solid 1px rgba(228, 228, 228, 1);
	width: 150px;
	height: 170px;
	display: inline-block;
	margin-left: 20px;
	}
</style>
